import { defineStore } from 'pinia'
import Notifier from 'src/helpers/Notifier'
import {api} from "boot/axios";
import {StudyPlan} from "src/models/study-plan";
import qs from "qs";
import {toRaw} from "vue";

export const studyPlansStore = defineStore('studyPlans', {
  state: () => ({
    studyPlansList: [],
    availableModalities: [],
    shiftTypes: [],
    scheduleTypes: [],
    editableDoctor: null,
    isEditing: false,
    creatableDoctor: null,
    isCreating: false
  }),

  getters: {
    getStudyPlansRows (state) {
      let wrapper = {}
      const rows = []

      state.studyPlansList.map((el) => {
        const studyPlan = toRaw(el)
        // TODO change to week
        wrapper[studyPlan.month] = {
          week: studyPlan.month
        }
      })

      state.studyPlansList.map((el) => {
        const studyPlan = toRaw(el)
        const normalizedUniqueStudyCode = studyPlan.study.modality.code + '/' + studyPlan.study.enhancement
        // TODO change to week
        wrapper[studyPlan.month][normalizedUniqueStudyCode]= {
          modality: studyPlan.study.modality,
          enhancement: studyPlan.study.enhancement,
          number_of_studies: studyPlan.number_of_studies,
          labor_intensity: studyPlan.study.labor_intensity,
          id: studyPlan.id
        }
      })

      Object.values(wrapper).forEach((el) => rows.push(el))

      return rows
    },
    getStudyPlansColumns(state) {
      let result = [{
        name: 'week',
        align: 'left',
        label: 'Неделя',
        field: 'week'
      }]

      state.studyPlansList.map((el) => {
        const studyPlan = toRaw(el)
        const normalizedUniqueStudyCode = studyPlan.study.modality.code + '/' + studyPlan.study.enhancement
        const normalizedUniqueStudyName = studyPlan.study.modality.name + '/' + studyPlan.study.enhancement
        const fieldCallback = (row, uniqueCode = normalizedUniqueStudyCode) => {
          return row[uniqueCode].number_of_studies
        }

        // TODO change to week
        result.push({
          name: normalizedUniqueStudyCode,
          label: normalizedUniqueStudyName,
          field: fieldCallback,
          align: 'center'
        })
      })

      return result
    }
  },

  actions: {
    async getForecastedStudyPlansList(payload) {
      try {
        const year = payload.split('/')[0]
        const month = payload.split('/')[1] ?? null

        const query = qs.stringify({
          year,
          ...(month && { month })
        })

        const response = await api.get(`/plans/forecast?${query}`) ?? []
        this.studyPlansList = response.data.map((el) => new StudyPlan(el))

        return this.studyPlansList
      } catch (err) {
        Notifier.error('Ошибка при загрузке списка пользователей')
        console.error(err)
        return err
      }
    },
  }
})
